#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from select import select
import sys
from time import sleep
import utils.ConfUtil 
import utils.CommonUtil
import utils.Log
import utils.DockerUtil
import utils.NacosUtil
log=utils.Log.getLogger()
argv=sys.argv[1:]
if len(argv)<2: 
    log.warning("usage: $0 SERVICE(服务名) PUBLISH(发布地址)")
    exit()
SERVICE=argv[0]
PUBLISH=argv[1]
log.debug("=========发版:"+SERVICE+" "+PUBLISH+"=========")
config=utils.ConfUtil.config('conf/publish.conf')
#判断是否存在服务配置
if SERVICE not in config.keys():
    log.error("服务"+SERVICE+"未配置在conf/publish.conf")
    exit()
#配置中获取用户名
USERNAME=config["IP2User"][PUBLISH]
#服务端口
PORT=config[SERVICE]["Port"]
SERVICE_GIT_PATH=config[SERVICE]["GitPath"]
NACOS_NAMESPACE=config[SERVICE]["NacosNamespace"]
NACOS_GROUPNAME=config[SERVICE]["NacosGroupName"]
GIT_ROOT_PATH=config["System"]["GitRootPath"]
HUB_HOST=config["System"]["DockerHubHost"]
JAVA_PARAMS=config["System"]["JavaParams"]
DOCKER_HUB=HUB_HOST+":5000"
DOCKER_IMAGE_PREFIX=config["System"]["DockerImagePrefix"]
VERSION=utils.CommonUtil.execCmd("cd "+GIT_ROOT_PATH+"&& git describe")
log.debug("发布"+SERVICE+"到docker hub")
log.debug("当前版本"+VERSION)
log.debug("发布到IP:"+PUBLISH)
#查看是否存在镜像，如果不存在则打包镜像
serviceCount=utils.DockerUtil.serviceCount(DOCKER_IMAGE_PREFIX,DOCKER_HUB,SERVICE,VERSION)
log.debug("当前版本镜像总数:"+serviceCount)
if serviceCount=='0':
    # log.debug("推送版本镜像")
    utils.DockerUtil.pushServiceImage(DOCKER_IMAGE_PREFIX,DOCKER_HUB,SERVICE,VERSION,SERVICE_GIT_PATH)
    utils.CommonUtil.execCmd("rm /tmp/"+DOCKER_IMAGE_PREFIX+SERVICE+"-"+VERSION)
    cmd="docker save "+DOCKER_HUB+"/"+DOCKER_IMAGE_PREFIX+SERVICE+":"+VERSION+" -o " + "/tmp/"+DOCKER_IMAGE_PREFIX+SERVICE+"-"+VERSION
    log.debug("保存镜像到本地"+cmd)
    utils.CommonUtil.execCmd(cmd)
if HUB_HOST!=PUBLISH:
    cmd="scp /tmp/"+DOCKER_IMAGE_PREFIX+SERVICE+"-"+VERSION+" "+USERNAME+"@"+PUBLISH+":/tmp/"
    log.debug("传送到目标机器镜像"+cmd)
    utils.CommonUtil.execCmd(cmd)    
NACOS_SERVER=config["System"]["NacosServer"]
log.debug("下线服务"+PUBLISH+":"+PORT)
utils.NacosUtil.offlineService(NACOS_SERVER,SERVICE,PUBLISH,PORT,NACOS_NAMESPACE,NACOS_GROUPNAME)
sleep(1)
SPRING_ENV=config["System"]["SpringEnv"]
DOCKER_PARAMS=config[SERVICE].get("DockerParams","")
if not DOCKER_PARAMS:
    DOCKER_PARAMS=""
publishShell=utils.DockerUtil.createPublishShell2(HUB_HOST,DOCKER_IMAGE_PREFIX,PUBLISH,SERVICE,VERSION,SPRING_ENV,PORT,JAVA_PARAMS,DOCKER_PARAMS)
SHELL_NAME="gen/"+SERVICE+"_publish.sh"
utils.CommonUtil.writeFile(SHELL_NAME,publishShell)
if HUB_HOST==PUBLISH:
    utils.CommonUtil.execCmd("sh "+SHELL_NAME)
else:
    utils.CommonUtil.execCmd("ssh -Tq "+USERNAME+"@"+PUBLISH+"<"+SHELL_NAME)

arry=["\\","|","/","-"]
TIMES=0
if "CheckHealth" in config[SERVICE].keys():
    checkHealth=config[SERVICE]["CheckHealth"]
    if checkHealth=="0":
        log.debug(SERVICE+" 发布完成")
        sys.exit(0)
    else :
        #先探测端口是否启动
        while True:
            status=utils.CommonUtil.getHealthStatus(PUBLISH+":"+PORT+'/actuator/health')
            if status!="UP":
                TIMES=TIMES+1
                print("等待服务启动: %c\r" % arry[TIMES%4],end="")
                sleep(1)
            else:
                log.debug("上线服务"+PUBLISH+":"+PORT)
                utils.NacosUtil.onlineService(NACOS_SERVER,SERVICE,PUBLISH,PORT,NACOS_NAMESPACE,NACOS_GROUPNAME)
                break
        while True:
            if utils.CommonUtil.getCheckHealthStatus(checkHealth)!=PUBLISH+":"+PORT:
                TIMES=TIMES+1
                print("等待服务启动: %c\r" % arry[TIMES%4],end="")
                sleep(1)
            else:
                log.debug("Nacos上线服务"+PUBLISH+":"+PORT)
                break
else:
    log.debug("默认启动10秒")
    sleep(10)
    #等待端口存在
    while True:
        status=utils.CommonUtil.httpStatus(PUBLISH+":"+PORT)
        if status=="000":
            TIMES=TIMES+1
            print("等待服务启动: %c\r" % arry[TIMES%4],end="")
            sleep(1)
        else:
            log.debug("上线服务"+PUBLISH+":"+PORT)
            utils.NacosUtil.onlineService(NACOS_SERVER,SERVICE,PUBLISH,PORT,NACOS_NAMESPACE,NACOS_GROUPNAME)
            break
#根据配置判断是否需要等待
WAIT_FINISH="1"
if "WaitFinish" in config[SERVICE].keys():
    WAIT_FINISH=config[SERVICE]["WaitFinish"]
if WAIT_FINISH=="1":
    #等待注册完
    while True:
        proccessNum=utils.NacosUtil.processNum(NACOS_SERVER,SERVICE,PUBLISH,PORT,NACOS_NAMESPACE,NACOS_GROUPNAME)
        if proccessNum=='0':
            TIMES=TIMES+1
            print("注册服务数:"+proccessNum+" 等待 %c\r" % arry[TIMES%4],end="")
            sleep(1)
        else:
            log.debug(PUBLISH+":"+PORT+"已上线")
            log.debug("部署下一个")
            break
log.debug(SERVICE+" 发布完成")